<?php 
namespace app\common\model;
use think\Model;
use think\Db;

class Menu extends Model
{
	public function menu($id)
	{
		if($id === "c"){
			$map['parent_id'] = array('in','1,2,3');
			$res = Db::name('category')->where($map)->select();
			return $res;
		}else if($id){
			$res = Db::name('category')->where('parent_id',$id)->select();
			return $res;
		}else {
			$res = Db::name('category')->where('parent_id',0)->select();
			return $res;
		}
	    
	}
	public function Mdel($id)
	{  
	    $db = Db('category')->field(['parent_id'])->where('cate_id',$id)->select();
	    foreach($db as $k => $v) {
	    $res = Db('category') -> where('cate_id', $v['parent_id'])->update(['hasChildren' => '']);
	    }
	    $tt = Db::name('category')->delete($id);
	    return $res;
	}
	
    public function  mtree($id){
		 if($id == 0){
			$list = db('category')
			    ->field(['cate_id','parent_id','cate_name','url'])
			    ->where('cate_id','between',[1,4])
			    ->select();
		}else{
			$list = db('category')
			    ->field(['cate_id','parent_id','cate_name','url'])
			    ->where('type',$id)
			    ->select();
		}
		
	    
        $tree = array();
        if (is_array($list)) {
            $tree = $this->getTree($list,$id);
        }
        return $tree;
    }
	public function getTree($list,$id,$level=0)
	{  
	    
        static $tree = array();
        foreach($list as $k => $v)
        {
            if($v['parent_id'] == $id)
            {         //父亲找到儿子
			    $v['level']=$level;
				$tree[] = $v;
                $this->getTree($list, $v['cate_id'],$level+1);
                
            }
        }
        return $tree;
	}
	public function add($shuju)
	{  
	    
	                $res = Db('category') -> insert($shuju);
	                return $res;
	}
}